package com.example.hydropowermanage.controller;

import com.example.hydropowermanage.pojo.User123;
import com.example.hydropowermanage.pojo.UtilityUsage;
import com.example.hydropowermanage.service.LoginService;
import com.example.hydropowermanage.service.lmpl.UtilityUsageServiceImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Component
public class ScheduledTasks {
    private final UtilityUsageServiceImpl waterElectricityService;
    private LoginService loginService;
    private final Random random = new Random();
    int count=0;
    public final static Calendar calendar = Calendar.getInstance();
    public ScheduledTasks(UtilityUsageServiceImpl waterElectricityService, LoginService loginService) {
        this.waterElectricityService = waterElectricityService;
        this.loginService = loginService;
        // 初始化时间为 2023 年 1 月
        calendar.set(2023, Calendar.JANUARY, 1);
    }

    @Scheduled(fixedRate = 50000) // 每 50000 毫秒（50秒）执行一次
    public void someScheduledTask() {
        // 每执行10次任务，更新月份
        if (++count == 2) {
            count = 0;
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.DAY_OF_MONTH, 15);
            if (calendar.get(Calendar.MONTH) == Calendar.JANUARY) {
                // 如果是一月，增加年份
                calendar.add(Calendar.YEAR, 1);
            }
        }else {
            calendar.add(Calendar.DAY_OF_MONTH, 10);
        }

        Date currentMonth = calendar.getTime();
//        System.out.println("currentMonth = " + currentMonth);
        List<User123> allUsers = loginService.getAllUsers();
        for (User123 user : allUsers) {
            List<UtilityUsage> usages = waterElectricityService.selectListByMonth(user.getId(), currentMonth);
            if (usages.isEmpty()) {
                // 如果没有当前月份的水电信息，就添加
                UtilityUsage usage = new UtilityUsage();
                usage.setUserId(user.getId());
                usage.setUsageMonth(currentMonth);
                usage.setTotalWaterUsage(0.0);
                usage.setTotalElectricityUsage(0.0);
                usage.setPerWaterPrice(user.getWaterPrice());
                usage.setPerElectricityPrice(user.getElectricityPrice());
                usage.setCost(0.0);
//                System.out.println(currentMonth);
                usage.setCreatedAt(currentMonth);
                usage.setUpdatedAt(currentMonth);

                waterElectricityService.addUtilityUsage(usage);
            } else {
                // 如果有当前月份的水电信息，就更新
                for (UtilityUsage usage : usages) {
                    Double totalWaterUsage = usage.getTotalWaterUsage();
                    Double totalElectricityUsage = usage.getTotalElectricityUsage();
                    usage.setTotalElectricityUsage(totalElectricityUsage + random.nextInt(100));
                    usage.setTotalWaterUsage(totalWaterUsage + random.nextInt(100));
                    usage.setCost(setCost(usage.getTotalWaterUsage() * usage.getPerWaterPrice() +
                            usage.getTotalElectricityUsage() * usage.getPerElectricityPrice()));
                    usage.setUpdatedAt(currentMonth);
                    waterElectricityService.updateById(usage);
                    //更新用户
                    updateuser(user);
                }
            }
        }

        System.out.println("定时任务执行了");
    }

    public void updateuser(User123 user123) {
        //更新用户的水电费用
        double waterConsumption = 0;
        double powerConsumption = 0;
        double totalCost = 0;
        List<UtilityUsage> all = waterElectricityService.findAllByUserId(user123.getId());
        for (UtilityUsage utilityUsage:all) {
            waterConsumption+= utilityUsage.getTotalWaterUsage();
            powerConsumption+= utilityUsage.getTotalElectricityUsage();
            totalCost+= utilityUsage.getCost();
        }
        user123.setWaterConsumption(waterConsumption);
        user123.setPowerConsumption(powerConsumption);
        user123.setTotalCost(setCost(totalCost));
        loginService.updateUser(user123);
    }

    public static double setCost(double cost) {
        BigDecimal bd = new BigDecimal(cost).setScale(2, RoundingMode.HALF_UP);
        System.out.println(bd.doubleValue());
        return  bd.doubleValue();

    }
}
